package com.chinatsp.onlineapp.utils;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import org.xutils.common.util.LogUtil;

import android.annotation.SuppressLint;

/**
 * 签名工具类
 */
@SuppressLint("DefaultLocale")
public class SignTool {

	/**
	 * 签名
	 * 
	 * @param infoMap
	 *            将所有的参数按照参数名ASCII正序排列，然后添加token到最后，做md5 hash。
	 * @param isToken
	 *            true Token false SmsToken
	 * @return
	 */

	public static String sign(Map<String, String> infoMap, boolean isToken) {
		boolean first = true;
		StringBuffer stringBuffer = new StringBuffer();
		Map<String, String> resultMap = sortMapByValue(infoMap); // 按Value进行排序
		for (Map.Entry<String, String> entry : resultMap.entrySet()) {
			if (first) {
				first = false;
			} else {
				stringBuffer.append("&");
			}
			stringBuffer.append(entry.getKey());
			stringBuffer.append("=");
			stringBuffer.append(entry.getValue());
		}

		if (isToken) {
			String token = "";
			// token =
			// MyApplication.getmPreferences().getString(Constant.TOKEN);
			LogUtil.v("--- token----" + token);
			stringBuffer.append(token);
		} else {
			String smsToken = "";
			// smsToken =
			// MyApplication.getmPreferences().getString(Constant.SMSTOKEN);
			LogUtil.v("--- smtokens----" + smsToken);
			stringBuffer.append(smsToken);
		}
		LogUtil.v("--- 签名--前----" + stringBuffer.toString());
		LogUtil.v("--- 签名-后----"
				+ MD5.md5(stringBuffer.toString()).toUpperCase());
		return MD5.md5(stringBuffer.toString()).toUpperCase();
	}

	/**
	 * 使用 Map按value进行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, String> sortMapByValue(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		Map<String, String> sortMap = new TreeMap<String, String>(
				new MapComparator());
		sortMap.putAll(map);
		return sortMap;
	}

	/**
	 * 比较器类 比较Map Key的大小
	 */
	public static class MapComparator implements Comparator<String> {

		public int compare(String me1, String me2) {
			return me1.compareTo(me2);
		}
	}
}
